package gui2.g1;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

@SuppressWarnings("serial")
public class EDTCorrectSW extends JFrame {

	private JProgressBar bar;
	private JButton load;

	public EDTCorrectSW() {
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		bar = new JProgressBar(0, 100);
		bar.setPreferredSize(new Dimension(400, 50));

		load = new JButton("Load!");
		load.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				//System.out.println(Thread.currentThread().getName());

				load.setEnabled(false);
				bar.setString("Loading...");
				bar.setStringPainted(true);

				new SwingWorker<Void, Integer>() {

					@Override
					protected Void doInBackground() throws Exception {
						for (int i = 0; i <= 100; i++) {
							publish(i);
							try {
								Thread.sleep((long) (Math.random() * 150));
							} catch (InterruptedException e1) {
								e1.printStackTrace();
							}
						}
						return null;
					}

					@Override
					protected void process(List<Integer> chunks) {
						int percent = chunks.get(0);
						bar.setValue(percent);
						bar.setString("Loading... " + percent + "%");
					}

					@Override
					protected void done() {
						bar.setValue(0);
						bar.setStringPainted(false);
						load.setEnabled(true);
					}
				}.execute();

			}
		});

		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(load, BorderLayout.NORTH);
		getContentPane().add(bar, BorderLayout.CENTER);
		pack();
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				JFrame f = new EDTCorrectSW();
				f.setLocationRelativeTo(null);
				f.setVisible(true);
			}
		});
	}
}
